package com.android.clinic.app.ui.doctor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.DoctorInfo;
import com.android.clinic.app.glide.ImageLoaderUtils;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.pay.ClinicAliPay;
import com.android.clinic.app.ui.pay.ClinicWeChatPay;
import com.android.clinic.app.ui.pay.OnWXPayCallbackListener;
import com.android.clinic.app.ui.pay.PayUtils;
import com.android.clinic.app.ui.widget.UIAlertView;
import com.android.clinic.app.utils.AppManager;
import com.android.clinic.app.utils.Constants;
import com.android.clinic.app.utils.PermissionUtils;
import com.android.clinic.app.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by cheng on 2018/2/9.
 * 购买服务
 */
public class BuyServiceActivity extends BaseActivity {

    private TextView tvServiceHint;

    private ImageView ivWxPay, ivAliPay;
    private String paymentId = "";
    private String inquiryType = "";  // 0:图文问诊;1:视频问诊;2:预约服务
    private boolean isPayType = true;
    private int appointId = 0;  // 预约ID

    private String payPrice = "";
    private String payTitle = "爱帮诊服务费";
    private DoctorInfo doctorInfo;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_buy_service;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("购买服务");
        setTitleBarLeftResource(R.drawable.icon_back);

        ImageView ivHead = (ImageView) findViewById(R.id.iv_head);
        TextView tvName = (TextView) findViewById(R.id.tv_name);
        TextView tvPriceTime = (TextView) findViewById(R.id.tv_price_of_time);
        TextView tvPrice = (TextView) findViewById(R.id.tv_price);
        tvServiceHint = (TextView) findViewById(R.id.tv_service_hint);
        TextView tvDefaultName = (TextView) findViewById(R.id.tv_default_name);
        FrameLayout layDefault = (FrameLayout) findViewById(R.id.layout_default);

        ivWxPay = (ImageView) findViewById(R.id.iv_wx_pay);
        ivAliPay = (ImageView) findViewById(R.id.iv_ali_pay);
        ivWxPay.setSelected(isPayType);

        doctorInfo = (DoctorInfo) this.getIntent().getSerializableExtra("doctorInfo");
        inquiryType = this.getIntent().getStringExtra("inquiryType");
        if (!"0".equals(inquiryType)) {
            appointId = this.getIntent().getIntExtra("appointId", 0);
        }

        if (!Utils.isEmpty(doctorInfo.getImgUrl()) && doctorInfo.getImgUrl().contains(".jpg")) {
            ivHead.setVisibility(View.VISIBLE);
            layDefault.setVisibility(View.GONE);
            ImageLoaderUtils.getInstance().loadHeadHomeImage(doctorInfo.getImgUrl(), ivHead);
        } else {
            ivHead.setVisibility(View.GONE);
            layDefault.setVisibility(View.VISIBLE);
            tvDefaultName.setText(doctorInfo.getName());
        }
        tvName.setText(doctorInfo.getName());
        tvServiceHint.setText("0".equals(inquiryType) ? "问诊服务" : "预约服务");
        // 1-视频问诊价格:899; 0-图文问诊、2-预约服务价格:399
        String videoPrice = Utils.isEmpty(doctorInfo.getVideoPrice()) ? Constants.VIDEO_PRICE : doctorInfo.getVideoPrice();
        String inquirePrice = Utils.isEmpty(doctorInfo.getInquirePrice()) ? Constants.INQUIRE_PRICE : doctorInfo.getInquirePrice();
        payPrice = "1".equals(inquiryType) ? videoPrice : inquirePrice;
        tvPriceTime.setText(payPrice);
        tvPrice.setText("实付" + payPrice + "元");
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            // 管家
            case R.id.tv_service:
                PermissionUtils.applyCallPhone(this, new PermissionUtils.CallBack() {
                    @Override
                    public void onGuarantee() {
                        UIAlertView.callPhoneDialog(BuyServiceActivity.this, "管家电话", "4001883525");
                    }

                    @Override
                    public void onDeny() {

                    }
                });
//                startActivity(new Intent(this, CustomerServiceActivity.class));
                break;
            // 微信支付
            case R.id.layout_wx_pay:
                isPayType = true;
                ivWxPay.setSelected(true);
                ivAliPay.setSelected(false);
                break;
            // 支付宝支付
            case R.id.layout_ali_pay:
                isPayType = false;
                ivWxPay.setSelected(false);
                ivAliPay.setSelected(true);
                break;
            // 去支付
            case R.id.tv_pay:
                if (isPayType) {
                    paymentOrderWithWeChat();
                } else {
                    paymentOrderWithALi();
                }
                break;
        }
    }

    /**
     * 获取支付宝支付订单
     */
    private void paymentOrderWithALi() {
        HttpClient.getHttpService().aliPay("爱帮诊支付", payTitle, payPrice,
                ClinicApplication.getUserInfo().getId())
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject json = jsonObject.getJSONObject("element");
                            paymentId = json.getString("paymentId");
                            updateAppointment(paymentId, json);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 获取微信支付订单
     */
    private void paymentOrderWithWeChat() {
        HttpClient.getHttpService().weChatPay(payTitle, payPrice,
                ClinicApplication.getUserInfo().getId())
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject json = jsonObject.getJSONObject("element");
                            paymentId = json.getString("paymentId");
                            updateAppointment(paymentId, json);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 更新预约状态(视频预约)
     */
    private void updateAppointment(String paymentId, JSONObject json) {
        String url = "1".equals(inquiryType)
                ? Constants.VIDEO_APPOINTING_URL + paymentId + "/" + appointId
                : Constants.APPOINTING_URL + paymentId + "/" + appointId;
        HttpClient.getHttpService().getAppointingById(url)
            .compose(this.bindToLifecycle())
            .compose(RxObservableUtils.applySchedulers())
            .subscribe(new BaseObserver<String>() {
                @Override
                public void onSuccess(String s){
                    tvServiceHint.setText("0".equals(inquiryType) ? "问诊服务" : "付款成功");
                    try {
                        if (isPayType) {
                            // 微信
                            paymentWithWeChat(json.getJSONObject("body"));
                        } else {
                            // 支付宝
                            paymentWithALi(json.getString("body"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(String message) {
                    showToast(message);
                }
            });

    }


    /**
     * 支付宝支付
     * @param orderInfo
     */
    private void paymentWithALi(String orderInfo) {
        ClinicAliPay clinicAliPay = new ClinicAliPay(BuyServiceActivity.this);
        clinicAliPay.aliPay(orderInfo);
        //支付宝支付状态
        clinicAliPay.setOnPaySuccessListener(new ClinicAliPay.OnPaySuccessListener() {
            @Override
            public void onSuccess() {
                if ("0".equals(inquiryType)) {
                    updateInquiryStatus();
                } else {
                    updateAppointSuccess();
                }
            }

            @Override
            public void onFailure() {
                showToast("支付失败");
                finish();
            }
        });
    }

    /**
     * 微信支付
     * @param data
     */
    private void paymentWithWeChat(JSONObject data) {
        ClinicWeChatPay weChatPay = new ClinicWeChatPay(BuyServiceActivity.this, data);
        weChatPay.initPay();
        PayUtils.getInstance().setCallBackListener(new OnWXPayCallbackListener() {
            @Override
            public void onSuccess() {
                if ("0".equals(inquiryType)) {
                    updateInquiryStatus();
                } else {
                    updateAppointSuccess();
                }
            }

            @Override
            public void onFailure(int errCode) {
                showToast("支付失败");
                finish();
            }
        });
    }

    /**
     * 问诊服务支付成功后状态
     */
    private void updateInquiryStatus() {
        UIAlertView.paySuccessDialog(BuyServiceActivity.this, new UIAlertView.OnThemeDialogListener() {
            @Override
            public void OnDismissButton() {

            }

            @Override
            public void OnSureButton() {
                Intent intent = new Intent(BuyServiceActivity.this, AskQuestionWithDoctorActivity.class);
                intent.putExtra("doctorId", doctorInfo.getId());
                startActivity(intent);
                finish();
            }
        });
    }

    /**
     * 支付成功后更新预约状态为成功
     */
    private void updateAppointSuccess() {
        String url = "1".equals(inquiryType)
                ? Constants.VIDEO_APPOINT_SUCCESS_URL + paymentId
                : Constants.APPOINT_SUCCESS_URL + paymentId;
        HttpClient.getHttpService().getAppointingSuccess(url)
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        tvServiceHint.setText("预约成功");
                        if ("1".equals(inquiryType)) {
                            showToast("完成付款, 医生会尽快与您联系");
                        } else {
                            showToast("预约成功");
                        }
                        AppManager.getAppManager().finishActivity(SitDiagnosedActivity.class);
                        finish();
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

}
